<?php
namespace user;
use View;
use Response;
use BaseController;
use Auth;
use User;
use Project;
use Input;
use Validator;
use Redirect;
class ProjectsController extends BaseController {

	/**
	 * Display a listing of the resource.
	 * GET /user/projects
	 *
	 * @return Response
	 */
	public function index()
	{
		$projects = Project::where('user_id',Auth::id())->orderBy('created_at','desc')->paginate(5);
		return View::make('user.projects.index')->with('title','开源项目')->with('projects',$projects);
	}

	public function add()
	{
		return View::make('user.projects.add')->with('title','开源项目');
	}

	public function doAdd(){
		$rules = array(
			'name' => 'required|min:6',
			'home_url' => 'required|url',
			'download_url' => 'required|url',
			'doc_url' => 'required|url'
		);
		
		$validator = Validator::make(Input::all(),$rules);
		if($validator->passes()){
			$project = Project::create(Input::only('name','home_url','download_url','doc_url','license','detail'));
			$project->user_id = Auth::id();
			if($project->save()){
				return Redirect::to('user/projects')->with('message',array('type'=>'success','content'=>'软件发布成功'));
			}else{
				return Redirect::back()->with('message',array('type'=>'danger','content'=>'软件发布失败'))->withInput();
			}
		}else{
			return Redirect::back()->withInput()->withErrors($validator);
		}
	}


	public function modify($id){
		return View::make('user.projects.modify')->with('project',Project::find($id))->with('title','开源项目');
	}

	public function doModify(){
		$rules = array(
			'name' => 'required|min:6',
			'home_url' => 'required|url',
			'download_url' => 'required|url',
			'doc_url' => 'required|url'
		);
		
		$validator = Validator::make(Input::all(),$rules);
		if($validator->passes()){
			$project = Project::find(Input::get('id'));
			$project->name = Input::get('name');
			$project->home_url = Input::get('home_url');
			$project->download_url = Input::get('download_url');
			$project->doc_url = Input::get('doc_url');
			$project->detail = Input::get('detail');
			if($project->save()){
				return Redirect::to('user/projects')->with('message',array('type'=>'success','content'=>'修改成功'));
			}else{
				return Redirect::back()->with('message',array('type'=>'danger','content'=>'修改失败'))->withInput();
			}
		}else{
			return Redirect::back()->with('message',array('type'=>'danger','content'=>'修改失败'))->withInput()->withErrors($validator);
		}
	}

	public function delete($id){
		$project = Project::find($id);
		if($project && $project->delete()){
			return Redirect::back()->with('message',array('type'=>'danger','content'=>'删除成功'));
		}else{
			return Redirect::back()->with('message',array('type'=>'success','content'=>'删除失败'));
		}
		
	}

}